package com.bupt.cad.controller;


import com.alibaba.fastjson.JSON;
import com.bupt.cad.common.ApiResult;
import com.bupt.cad.entity.DataSource;
import com.bupt.cad.entity.DataSourceVo;
import com.bupt.cad.service.impl.DataSourceService;
import com.bupt.cad.utils.CsvUtil;
import com.bupt.cad.utils.ResultUtil;
import org.jumpmind.symmetric.csv.CsvReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
//import com.csvreader.CsvReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class DataSourceController {
    @Autowired
    private DataSourceService dataSourceService;

    @ResponseBody
    @PostMapping(value = "/upload/dataSource")
    public ApiResult insert(@RequestParam("file") MultipartFile multipartFile,
                            @RequestParam("name") String name,
                            @RequestParam("screenId") int screenId,
                            HttpServletRequest request) {

        int id = dataSourceService.insertDataSource(multipartFile,name,screenId);
        if(id!=0){
            Map<String,Object> map = new HashMap<>();
            map.put("id",id);
            map.put("name",name);
            return ResultUtil.success(map,"upload csv file successfully");
        }
        else{
            return ResultUtil.error(-1,"failed");
        }
    }
    //根据id获取数据源
    @ResponseBody
    @GetMapping(value = "/get/dataSource")
    public ApiResult get(@RequestParam("dataSourceId") int id){
        DataSource dataSource = dataSourceService.getDataSource(id);
        if(dataSource!=null){
            return ResultUtil.success(dataSource,"get datasource successfully");
        }else{
            return ResultUtil.error(-1,"get datasource failed");
        }
    }
    //根据大屏id获取所有数据源
    @ResponseBody
    @GetMapping(value = "/getAll/dataSource")
    public ApiResult getAll(@RequestParam("screenId") int id){
        List<DataSourceVo> dataSources = dataSourceService.getAllDataSource(id);
        if(dataSources!=null){
            return ResultUtil.success(dataSources,"getAll datasource successfully");
        }
        else{
            return ResultUtil.error(-1,"getAll datasource failed,maybe datasource is null or get error");
        }
    }

}
